package com.feijia.aijingjingus;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.RelativeSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.conn.BleGattCallback;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.exception.BleException;
import com.plattysoft.leonids.ParticleSystem;
import com.plattysoft.leonids.modifiers.ScaleModifier;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static com.feijia.aijingjingus.GlobalHelper.AD1;
import static com.feijia.aijingjingus.GlobalHelper.AD1List;
import static com.feijia.aijingjingus.GlobalHelper.AD2;
import static com.feijia.aijingjingus.GlobalHelper.AD2List;
import static com.feijia.aijingjingus.GlobalHelper.ADRecord;
import static com.feijia.aijingjingus.GlobalHelper.BatteryValue;
import static com.feijia.aijingjingus.GlobalHelper.BleAddress;
import static com.feijia.aijingjingus.GlobalHelper.BleB;
import static com.feijia.aijingjingus.GlobalHelper.BleBeatsSpan;
import static com.feijia.aijingjingus.GlobalHelper.BleBuffer;
import static com.feijia.aijingjingus.GlobalHelper.BleData;
import static com.feijia.aijingjingus.GlobalHelper.BleDisconnCountDown;
import static com.feijia.aijingjingus.GlobalHelper.BleG;
import static com.feijia.aijingjingus.GlobalHelper.BleHandler;
import static com.feijia.aijingjingus.GlobalHelper.BleR;
import static com.feijia.aijingjingus.GlobalHelper.BleReadCount;
import static com.feijia.aijingjingus.GlobalHelper.BleScanTime;
import static com.feijia.aijingjingus.GlobalHelper.CYConn;
import static com.feijia.aijingjingus.GlobalHelper.DEBUG_MODE;
import static com.feijia.aijingjingus.GlobalHelper.DEBUG_MODE_SHOW_AD;
import static com.feijia.aijingjingus.GlobalHelper.DEBUG_MODE_SHOW_TOAST_AD;
import static com.feijia.aijingjingus.GlobalHelper.DNum;
import static com.feijia.aijingjingus.GlobalHelper.DetectionLocation;
import static com.feijia.aijingjingus.GlobalHelper.DetectionResults;
import static com.feijia.aijingjingus.GlobalHelper.DetectionType;
import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.Mode;
import static com.feijia.aijingjingus.GlobalHelper.NeedUploadDetection;
import static com.feijia.aijingjingus.GlobalHelper.NeedUploadDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBuffer;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBufferSize;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBufferTwo;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBufferTwoSize;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataCount;
import static com.feijia.aijingjingus.GlobalHelper.REQUEST_FINE_LOCATION;
import static com.feijia.aijingjingus.GlobalHelper.RawDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.ReadCount;
import static com.feijia.aijingjingus.GlobalHelper.Report;
import static com.feijia.aijingjingus.GlobalHelper.SHOW_DYNAMIC_VALUE;
import static com.feijia.aijingjingus.GlobalHelper.ShowAD;
import static com.feijia.aijingjingus.GlobalHelper.ShowRGB;
import static com.feijia.aijingjingus.GlobalHelper.Temperature;
import static com.feijia.aijingjingus.GlobalHelper.TemperatureDetect;
import static com.feijia.aijingjingus.GlobalHelper.UploadRawDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.bleManager;
import static com.feijia.aijingjingus.GlobalHelper.handler;
import static com.feijia.aijingjingus.GlobalHelper.isBleConnectingOrConnected;
import static com.feijia.aijingjingus.GlobalHelper.isBleRescanThreadRunning;
import static com.feijia.aijingjingus.GlobalHelper.isNeedInitBle;
import static com.feijia.aijingjingus.GlobalHelper.isNetOut;
import static com.feijia.aijingjingus.GlobalHelper.isPingSuccess;
import static com.feijia.aijingjingus.GlobalHelper.tip;

public class temperatureActivity extends AppCompatActivity {
    Context context;
    LineChartView chartView;
    LineChartData chartData;
    //Random random = new Random();
    List<PointValue> pointValues = new ArrayList<>();
    List<PointValue> pointValues2 = new ArrayList<>();
    List<PointValue> pointValues3 = new ArrayList<>();
    List<PointValue> pointValuesR = new ArrayList<>();
    List<PointValue> pointValuesG = new ArrayList<>();
    List<PointValue> pointValuesB = new ArrayList<>();
    List<PointValue> pointValuesAD1 = new ArrayList<>();
    List<PointValue> pointValuesAD2 = new ArrayList<>();
    ArrayList<AxisValue> axisValuesX = new ArrayList<>();
    Axis axisX = new Axis();
    ArrayList<AxisValue> axisValuesY = new ArrayList<>();
    Axis axisY = new Axis().setHasLines(true).setTextSize(10);
    List<Line> lines = new ArrayList<>();
    float progress = 1;
    Viewport v;
    //Handler handler;
    int TimeCount = 0;
    private static final int TimeCountMax = 70;
    private static final int ChartW = 26;
    private static final int GetDataTimeSpan = BleBeatsSpan;
    private static final float Step = 1.6f;
    private int DataCount = 0;
    private double DataSum = 0;
    private TextView tvDetectValue, tvIU,tvShowTemperature;
    private RelativeLayout rlBeforeDetect,rlDetect;
    Thread updatePoint;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temperature);
        TemperatureDetect=true;
        final Handler handler = new Handler();
        context = this;
        chartView = (LineChartView) findViewById(R.id.lineChart);
        tvShowTemperature= (TextView) findViewById(R.id.tvShowTemperature);
        rlBeforeDetect = (RelativeLayout)findViewById(R.id.rlBeforeDetect);
        rlDetect = (RelativeLayout)findViewById(R.id.rlDetect);

        for (int i = 0; i < TimeCountMax; i += 5) {
            int x = i;
            int y = 10;
            //pointValues.add(new PointValue(x, y));
            //pointValues3.add(new PointValue(x, y));
            axisValuesX.add(new AxisValue(x).setValue(x).setLabel(""));

        }
        for(int i = 0; i < 6; i+= 1){
            axisValuesY.add(new AxisValue(i).setValue(i*10).setLabel(""+(i*10)));
        }

        //axisValuesY.add(new AxisValue(0).setValue(10));
        pointValues2.add(new PointValue(0, 0));
        pointValues2.add(new PointValue(TimeCountMax, 40));
        axisX.setValues(axisValuesX);
        //axisX.setHasLines(true);
        //axisX.setTextColor(getResources().getColor(R.color.zero));
        axisY.setValues(axisValuesY);
        axisY.setHasLines(true);
        Line line = new Line(pointValues);
        line.setHasLabels(true);
        line.setCubic(true);
        line.setCubic(true);
        line.setHasPoints(false);
        lines.add(line);
        Line line3 = new Line(pointValues3);
        line3.setHasLabels(true);
        line3.setCubic(true);
        line3.setCubic(true);
        line3.setHasPoints(false);
        lines.add(line3);
        Line line2 = new Line(pointValues2);
        line2.setColor(ContextCompat.getColor(context, R.color.zero));
        lines.add(line2);
        Line lineR = new Line(pointValuesR);
        Line lineG = new Line(pointValuesG);
        Line lineB = new Line(pointValuesB);
        Line lineAD1 = new Line(pointValuesAD1);
        Line lineAD2 = new Line(pointValuesAD2);
        lines.add(lineR);
        lines.add(lineG);
        lines.add(lineB);
        lines.add(lineAD1);
        lines.add(lineAD2);
        chartData = new LineChartData(lines);
        //chartData.setBaseValue(10);
        chartData.setAxisXBottom(axisX);
        /*
        if(!DEBUG_MODE)
            axisY.setTextColor(ContextCompat.getColor(context, R.color.zero));

        chartData.setAxisYLeft(axisY);
        */
        if (DEBUG_MODE)
            chartData.setAxisYLeft(axisY);
        chartData.setValueLabelBackgroundEnabled(false);
        chartData.setValueLabelTextSize(10);
        chartView.setLineChartData(chartData);
        //chartView.setScrollEnabled(false);
        v = new Viewport(chartView.getMaximumViewport());
        v.left = 0;
        v.right = ChartW;
        chartView.setCurrentViewport(v);


        updatePoint = new Thread(new Runnable() {
            @Override
            public void run() {
                int timeSpan = 50;
                int count = 0;
                final RelativeLayout rlResult = (RelativeLayout) findViewById(R.id.ShowResultRelativeLayout);
//                final TextView tvBatteryValue = (TextView) findViewById(R.id.tvBatteryValue);

                while (progress < 100&& isBleConnectingOrConnected/* || TestPCB*/) {

                    BleHandler.sendEmptyMessage(3);
                    try {
                        Thread.sleep(timeSpan);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(false&&Temperature==0&&rlDetect.getVisibility()==View.VISIBLE)
                    {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                //连接失败
                                rlDetect.setVisibility(View.GONE);
                                rlBeforeDetect.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                    //System.out.println("Ble newest "+NewestDetectDataBuffer[0]+"  "+NewestDetectDataBuffer[1]+"  "+NewestDetectDataBuffer[2]);

                    if (progress < 100 && count % (1000 / timeSpan) == 0) {
                        if (BleDisconnCountDown + 1 <= 0) {
                            //BleHandler.sendEmptyMessage(1);
                        }
                        BleDisconnCountDown--;
                    }


                    if (count % (GetDataTimeSpan * 1000 / timeSpan) == 0&&Temperature!=0) {
                        Line line2 = new Line(pointValues2);
                        line2.setColor(ContextCompat.getColor(context, R.color.zero));
                        lines.set(1, line2);

                        if (DEBUG_MODE) {
                            pointValuesAD1.add(new PointValue().set(TimeCount - 5, (float) Temperature).setLabel(String.format("%.1f", Temperature)));
                        } else {
                            pointValuesAD1.add(new PointValue().set(TimeCount - 5, (float)Temperature));
                        }
                        Line lineAD1 = new Line(pointValuesAD1);
                        lineAD1.setCubic(true);
                        if (DEBUG_MODE)
                            lineAD1.setHasLabels(true);
                        lineAD1.setHasPoints(true);
                        lineAD1.setPointRadius(3);
                        lineAD1.setColor(ContextCompat.getColor(context, R.color.ChartRed));
                        lines.set(6, lineAD1);

                        //lines =  new ArrayList<Line>(){{add(line); add(line2);}};
                        chartData = new LineChartData(lines);
                        //chartData.setBaseValue(10);
                        chartData.setValueLabelBackgroundEnabled(false);
                        chartData.setValueLabelTextSize(10);
                        chartData.setAxisXBottom(axisX);
                        /*
                        if(!DEBUG_MODE)
                            axisY.setTextColor(ContextCompat.getColor(context, R.color.zero));

                        chartData.setAxisYLeft(axisY);
                        */
                        chartData.setAxisYLeft(axisY);
                        chartView.setLineChartData(chartData);
                        //if(CYConn&&ShowAD)
                        v.top = 40;
                        if (TimeCount > ChartW) {
                            v.left = TimeCount - ChartW;
                            v.right = TimeCount;
                        }
                        chartView.setCurrentViewport(v);
                        if (DEBUG_MODE || DEBUG_MODE_SHOW_AD || DEBUG_MODE_SHOW_TOAST_AD) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                tvShowTemperature.setText(String.format("%.1f", Temperature));
                                //Toast.makeText(context, BleAddress, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        TimeCount += GetDataTimeSpan;
                    }
                    count++;

                }
            }
        });

    }
    public void onClickSendMsg(View view){
        BleHandler.sendEmptyMessage(0);
        updatePoint.start();
        if(rlDetect.getVisibility()==View.GONE)
        {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    rlDetect.setVisibility(View.VISIBLE);
                    rlBeforeDetect.setVisibility(View.GONE);
                }
            });
        }
    }
    public void onClickOpenSetting(View view){
        RelativeLayout rlMenu = (RelativeLayout)findViewById(R.id.rlMenu);
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator ani = ObjectAnimator.ofFloat(rlMenu, "translationX", 0, -1000).setDuration(200);
        set.play(ani);
        set.start();
    }
    public void onClickCloseSetting(View view){
        RelativeLayout rlMenu = (RelativeLayout)findViewById(R.id.rlMenu);
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator ani = ObjectAnimator.ofFloat(rlMenu, "translationX", -1000, 0).setDuration(200);
        set.play(ani);
        set.start();
    }
    public void onClickSendDisconnectMsg(View view){
        BleHandler.sendEmptyMessage(1);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            Intent intent = new Intent("controlCenterActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
        return false;
    }
}
